04. Thymeleaf - Condition

035ND C01 L03 A06 THYMELEAF CONDITION

Instructions

Let’s update our controller. Demo

@RequestMapping("demo")
public String demo(Model model) {
   model.addAttribute("message", "Hello Thymeleaf");
   double grade = 90.5;
   model.addAttribute("grade", grade);
   model.addAttribute("GPA", convertGPA(grade));
   // return to templates/demo.html page.

   return "demo";
}

private String convertGPA(double grade) {
   if (grade >= 90) {
       return "A";
   } else if (grade < 90 && grade >= 80) {
       return "B";
   } else if (grade < 80 && grade >= 70) {
       return "C";
   } else if (grade < 70 && grade >= 60) {
       return "D";
   } else {
       return "F";
   }
}

Then update our view, add the following code before

<h3>Exam Results</h3>
<div th:if="${grade} >= 60">
   You passed the exam.
   <div th:switch="${GPA}">You are
       <span th:case="A">Excellent</span>
       <span th:case="B">Good</span>
       <span th:case="C">Okay</span>
       <span th:case="D">Need improvement</span>
   </div>
</div>
<div th:if="${grade} < 60">
   You failed the exam.
</div>

Run the application, goto localhost:8080/demo

Demo

035ND C01 L03 A07 THYMELEAF CONDITION EXAMPLE